<?php
/**
 * 微信页面基础控制器（微网站相关）
 * @author duanlang<duanlang@iyene.com>
 * @reviewer author<xxxx@iyene.com>
 * 爱聚基础控制器基类，一些公用的常用的用的地方比较多的方法放在本地方
 */

use common\components\helpers\Uri;
use common\components\Logger;
use common\components\objects\WechatApp;
use common\controllers\WechatPublicController;
use EasyWeChat\Foundation\Application;

/**
 * 微信私人页面控制器, 所有的页面
 * Class WECHAT_Controller
 *
 * @author jiaozi--zhuzhenxing
 * @property Weixin_auth $weixinAuth
 * @property wechat_service $wechat_service
 */
class WECHAT_Controller extends WechatPublicController
{
    /**
     * 公众号主键ID
     * @var int
     */
    public $public_id;

    /**
     * 公司ID
     * @var int
     */
    public $visit_id;

    /**
     * 公司ID
     * @var int
     */
    public $company_id;

    /**
     * 应用信息
     * @var array
     */
    public $appInfo;

    /**
     * 主题
     * @var string
     */
    public $crm_theme;

    /**
     * @var WechatApp
     */
    public $wechatApp;

    public $weixinInfo;

    /**
     * 公司信息
     * @var array
     */
    public $company;

    /**
     * 活动助手授权信息
     *
     * @var array
     */
    public $wechatOauthInfo;

    /**
     * @var Application
     */
    public $weChat;

    /**
     * 用户OpenId.
     * 粉丝在用户公众号下面的openId, 如果无法获取(比如说公众号是订阅号), 这个值是空的. 
     * @var string
     */
    public $openid;

    /**
     * 当前公众号app_id
     * @var string
     */
    public $app_id;

    //构造函数
    function __construct(){
        parent::__construct();

        //初始化微信基类
        $this->_initialize();

        if(!empty($this->weixinInfo['authorizer_appid'])) {
            $this->wechatApp = WechatApp::create(
                $this->weixinInfo['id'],
                $this->weixinInfo['authorizer_appid'],
                $this->company_id,
                $this->visit_id
            );
        } else {
            Logger::log('这里竟然没有weixinInfo, ' . __FILE__ . ':' . __LINE__);
        }
    }

    /**
     * 系统初始化
     * @author duanlang<duanlang@iyene.com>
     */
    private function _initialize()
    {
        //非授权下执行(预览的情况也不执行下列代码)
        if($this->router->fetch_class() != 'wechat_oauth' && $this->input->get_post('preview') != 1){
            //获取公众账号id
            $this->public_id = intval($this->uri->segment(4));

            //获取当前访问的商户身份(公众账号)
            $this->load->model('weixin_auth', 'weixinAuth', 'default', '', false);

            $this->weixinInfo = $this->weixinAuth->getValidAuthById($this->public_id);
            if(empty($this->weixinInfo)) {
                return $this->show_error("未找到该用户的公众账号信息", 1);
            }

            //获取对于的商户账户信息
            $this->load->model('company' , 'companyModel' , 'default');
            $this->company = $this->companyModel->info(array('where' => array('id' => $this->weixinInfo['company_id'])));
            if(empty($this->company)) {
                return $this->show_error("访问的该账户不存在", -2);
            }

            $this->visit_id = $this->company['visit_id'];
            $this->company_id = $this->company['id'];

            $app_class_name = $this->uri->segment(2);

            //获取当前应用信息
            $this->load->model('application', 'applicationModel', 'default');
            $this->appInfo = $this->applicationModel->info(array('where' => array('class' => $app_class_name)));

            //检测是否微信应用，如果微信应用必须在微信下访问
            if(!empty($this->appInfo) && $this->appInfo['is_wechat'] == 1) {
                $user_agent = $_SERVER['HTTP_USER_AGENT'];
                if (strpos($user_agent, 'MicroMessenger') === false) {
                    // 非微信浏览器禁止浏览
                    return $this->show_error("请在微信客户端访问", 1);
                }
            }

            $this->wechatOauthInfo = $this->session->userdata('wechatOauthInfo');//获取活动助手的授权信息
            //检测会话情况(正常授权)
            if (!empty($this->wechatOauthInfo) && $this->wechatOauthInfo['id'] == $this->public_id) {
                //应用需要服务号访问但是该公众号不是服务号
                if (!empty($this->appInfo) && $this->appInfo['wechat_service_type'] == 2 && $this->weixinInfo['service_type_info'] != 2) {
                    return $this->show_error("该公众账号无法使用该功能,非服务号不可以访问", 1);
                }

                //如果是认证的服务号则检测粉丝id
                if($this->weixinInfo['service_type_info'] > 1 && $this->weixinInfo['verify_type_info'] == 0){
                    //粉丝id不存在则重新授权
                    if (empty($this->wechatOauthInfo['fansInfo'])) {
                        $this->wechat_oauth();
                    }
                }

                // 粉丝在用户公众号下面的openId, 如果无法获取, 这个值是空的.
                $this->openid = !empty($this->wechatOauthInfo['fansInfo']) ? $this->wechatOauthInfo['fansInfo']['openid'] : '';//粉丝openid

                // zuowei 2017/12/12 黑名单限制
                $con = array();
                $con['where']['company_id'] = $this->company_id;
                $con['where']['appid'] = $this->wechatOauthInfo['wechatPublicAccount']['appid'];
                $con['where']['openid'] = $this->openid;
                $this->load->model('weixin_blacklist' , 'BlackListModel' , 'default' , '' ,false);
                $isBlackList = $this->BlackListModel->info($con);
                if(!empty($isBlackList)){
                    return $this->show_error("活动已结束", 1);
                }

                //载入微信service
                $this->load->service('wechat_service');
                //根据微信公众账号id初始化微信对象

                $wechatInitialize = $this->wechat_service->weChatInitialize($this->company_id, $this->weixinInfo['authorizer_appid']);
                if($wechatInitialize['code'] > 0) {
                    //清理掉所有session
                    return $this->show_error("公众账号权限初始化异常,请重试", 1);
                }

                //常用的全局变量
                $this->weChat = $wechatInitialize['data'];
                $this->app_id = $this->weChat->config['app_id'];

                //jssdk处理
                $jssdkData = $this->weChat->js->config(true);
                $jssdk_config['appid'] = $this->app_id;
                $jssdk_config['timestamp'] = $jssdkData['timestamp'];
                $jssdk_config['nonceStr'] = $jssdkData['nonceStr'];
                $jssdk_config['signature'] = $jssdkData['signature'];
                $data['jssdk_config']    = json_encode($jssdk_config);

                $data['visit_id'] = $this->visit_id;
                $data['company_id'] = $this->company_id;
                $data['public_id'] = $this->public_id;
                $data['openid'] = $this->openid;
                $data['re_openid'] = $this->wechatOauthInfo['openid'];//活动助手授权的openid
                $data['userInfo'] = $this->wechatOauthInfo;
                //构造token数据
                $tokenInfo['visit_id'] = $this->company['visit_id'];

                //生成授权token
                $data['token'] = parent::getToken();
                //常用模板变量
                $data['static_url'] = config_item('static_url');
                $data['home_url']   = config_item('base_url');
                $data['mobile_url'] = config_item('mobile_url');
                $data['api_static_url'] = config_item('api_static_url');
                $data['app_type'] = APP_TYPE_USER;
                $data['is_https'] = is_HTTPS();
                $data['wechatInfo'] = $this->weixinInfo;
                $this->load->vars($data);

            } else {
                $this->wechat_oauth();
            }
        }
    }

    /**
     * 微信授权方法
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @return void
     */
    public function wechat_oauth()
    {
        //清除当前的会话
        $this->session->unset_userdata('wechatOauthInfo');

        $domain = substr(config_item('base_url'), 0, strlen(config_item('base_url')) -1);
        $target_url = !empty($target_url)? $target_url: $domain.$_SERVER['REQUEST_URI'];

        $redirectUri = Uri::controller('mobile/wechat_oauth_h5/index/' . $this->public_id, [
            'target_url' => $target_url
        ]);

        redirect($redirectUri);
    }
}
